package com.irate.adapter;

import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.irate.activity.R;
import com.irate.cache.ImageFetcher;
import com.irate.cache.RecyclingImageView;
import com.irate.dao.UserSearchFriendDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.model.UserSearchFriend;

public class SearchFriendAdapter extends BaseAdapter {

	protected List<UserSearchFriend> ldata;
	protected UserSearchFriendDAO userSDAO;
	protected ProgressDialog dialog;
	protected Context context;
	protected LinearLayout is_requested;
	protected ImageFetcher imageFetcher;

	public SearchFriendAdapter(List<UserSearchFriend> data, Context ct,
			ImageFetcher imgfet) {
		ldata = data;
		userSDAO = new UserSearchFriendDAO();
		context = ct;
		imageFetcher = imgfet;
	}

	@Override
	public int getCount() {
		return ldata.size();
	}

	@Override
	public Object getItem(int arg0) {
		return ldata.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		return Integer.parseInt(((UserSearchFriend) getItem(arg0)).getId());
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(parent.getContext());
			convertView = inflater.inflate(
					R.layout.friend_layout_item_search_friend, null);
		}

		// ImageView image =
		// (ImageView)convertView.findViewById(R.id.search_friend_image);
		TextView email = (TextView) convertView
				.findViewById(R.id.search_friend_email);
		RecyclingImageView imageView = (RecyclingImageView) convertView
				.findViewById(R.id.search_friend_image);
		ImageView isFriend = (ImageView) convertView
				.findViewById(R.id.search_friend_add_friend_button);
		LinearLayout send_request = (LinearLayout) convertView
				.findViewById(R.id.request_has_been_send);
		is_requested = (LinearLayout) convertView
				.findViewById(R.id.accept_request);

		final UserSearchFriend usf = (UserSearchFriend) getItem(position);
		email.setText(usf.getEmail());

		// if (usf.getUser_photo() == null || usf.getUser_photo().equals("") ||
		// usf.getUser_photo().equals("null")) {
		//
		// imageFetcher
		// .loadImage(
		// "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQgDkbd_NkJZWeX8JnOsoVkotByhnQ2GWhMAaUvFolz6QaL29eysA",
		// imageView);
		// } else {
		// imageFetcher.loadImage(usf.getUser_photo().contains("https://graph.facebook.com")?"":Constant.URL_IMAGE
		// + usf.getUser_photo(), imageView);
		imageFetcher.loadImage(usf.getUser_photo(), imageView);
		// }

		if (usf.getIsFriend().equals("true")) {
			isFriend(isFriend, send_request, is_requested);
		} else {
			if (!usf.getSend_request().equals("false")) {
				isSendRequestByMe(isFriend, send_request, is_requested);

			} else {
				if (!usf.getIs_requested().equals("false")) {
					isSentRequestBySomeOne(isFriend, send_request,
							is_requested, usf.getIs_requested());
				} else {
					makeFriend(isFriend, usf, send_request);
				}
			}

		}

		return convertView;
	}

	private void makeFriend(ImageView isFriend, final UserSearchFriend usf,
			LinearLayout send_request) {
		isFriend.setVisibility(View.VISIBLE);

		send_request.setVisibility(View.GONE);
		is_requested.setVisibility(View.GONE);

		isFriend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				InputMethodManager inputMethodManager = (InputMethodManager) context
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				if (inputMethodManager.isAcceptingText())
					inputMethodManager.hideSoftInputFromWindow(
							((Activity) context).getCurrentFocus()
									.getWindowToken(), 0);

				v.setVisibility(View.GONE);
				dialog = ProgressDialog.show(context, context.getResources()
						.getString(R.string.send_request), context
						.getResources().getString(R.string.loading), true);
				userSDAO.sendRequestFriend(usf.getId(),
						handlerSendRequestFriend, context, dialog);
				ldata.remove(usf);
				notifyDataSetChanged();

			}
		});
	}

	private void isSentRequestBySomeOne(ImageView isFriend,
			LinearLayout send_request, LinearLayout is_requested,
			final String request_id) {
		isFriend.setVisibility(View.GONE);
		send_request.setVisibility(View.GONE);
		is_requested.setVisibility(View.VISIBLE);

		TextView tv_accept = (TextView) is_requested.findViewById(R.id.accept);
		TextView tv_deny = (TextView) is_requested.findViewById(R.id.deny);

		tv_accept.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog = ProgressDialog.show(context, context.getResources()
						.getString(R.string.accept), context.getResources()
						.getString(R.string.loading), true);
				userSDAO.acceptRequestFriend(request_id, handlerAcceptFriend,
						context, dialog);
			}
		});

		tv_deny.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog = ProgressDialog.show(context, context.getResources()
						.getString(R.string.deny), context.getResources()
						.getString(R.string.loading), true);
				userSDAO.denyRequestFriend(request_id, handlerDenyFriend,
						context, dialog);
			}
		});

	}

	private void isSendRequestByMe(ImageView isFriend,
			LinearLayout send_request, LinearLayout is_requested) {
		isFriend.setVisibility(View.GONE);
		send_request.setVisibility(View.VISIBLE);
		is_requested.setVisibility(View.GONE);

		ImageView deleteRequest = (ImageView) send_request
				.findViewById(R.id.request_remove);

		deleteRequest.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});

	}

	private void isFriend(ImageView isFriend, LinearLayout send_request,
			LinearLayout is_requested) {
		isFriend.setVisibility(View.GONE);
		send_request.setVisibility(View.GONE);
		is_requested.setVisibility(View.GONE);
	}

	AsyncHttpResponseHandler handlerSendRequestFriend = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");
			Toast.makeText(
					context,
					context.getResources().getString(
							R.string.send_request_success), Toast.LENGTH_LONG)
					.show();
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(context, obj.getString("message").toString(),
						Toast.LENGTH_SHORT).show();
			} catch (Exception ex) {

			}
		}
	};

	AsyncHttpResponseHandler handlerAcceptFriend = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");
			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(context, obj.getString("message").toString(),
						Toast.LENGTH_SHORT).show();

			} catch (Exception ex) {

			}

			if (is_requested != null) {
				is_requested.setVisibility(View.GONE);
			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(context, obj.getString("message").toString(),
						Toast.LENGTH_SHORT).show();

			} catch (Exception ex) {

			}
		}
	};

	AsyncHttpResponseHandler handlerDenyFriend = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Success register");
			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(context, obj.getString("message").toString(),
						Toast.LENGTH_SHORT).show();

			} catch (Exception ex) {

			}

			if (is_requested != null) {
				is_requested.setVisibility(View.GONE);
			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(context, obj.getString("message").toString(),
						Toast.LENGTH_SHORT).show();

			} catch (Exception ex) {

			}
		}
	};

}
